//
//  UIKPickerView.swift
//  Preferential
//
//  Created by Fineland on 2021/3/17.
//

class UIKPickerView: UIView, UIPickerViewDelegate, UIPickerViewDataSource {

    //picker对象
    private var pickerView: UIPickerView!
    //当前索引
    private var currIndex: Int = 0
    
    //刷新列表
    var data: Array<NSKPickerModel> = []
    
    //闭包
    typealias ReturnClosure = (_ isValue: Bool, _ value: NSKCellValueModel) -> Void
    //回调
    var operationClosure: ReturnClosure?
    
    //选中索引
    var selectedIndex: Int {
        
        set {
            //默认值
            currIndex = 0
            if newValue > -1 && newValue < data.count {
                currIndex = newValue
            }
        }
        get {
            return currIndex
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //创建视图
        setupViews()
        //属性
        self.backgroundColor = UIColor.white
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */
    
    private func setupViews() -> Void {
        
        let wVa: CGFloat = UIScreen.main.bounds.size.width
        //取消、确定
        let szButton = CGSize(width: 54.0, height: 44.0)
        let cancelButton = button(with: CGRect(origin: CGPoint.zero, size: szButton), title: "取消",
                                  textColor: NSKVar.C9_COLOR, tag: 0)
        let okButton = button(with: CGRect(origin: CGPoint(x: wVa - szButton.width, y: 0.0),
                                           size: szButton),
                              title: "确定", textColor: NSKVar.MAIN_COLOR, tag: 1)
        //picker视图
        pickerView = UIPickerView(frame: CGRect(x: 0.0, y: okButton.frame.maxY, width: wVa, height: 216.0))
        pickerView.delegate = self
        pickerView.dataSource = self
        //添加
        self.addSubview(pickerView)
        self.addSubview(cancelButton)
        self.addSubview(okButton)
        //调整RECT值
        var rect = self.frame
        rect.size.height = pickerView.frame.maxY + safeArea()
        self.frame = rect
    }
    
    @objc func nextTouched(_ sender: UIButton) -> Void {
        
        var valueObj = NSKCellValueModel()
        var tempVal = false
        //是否为确定？
        if sender.tag > 0 {
            //当前对象
            let pickerObj = data[currIndex]
            valueObj = NSKCellValueModel(value: pickerObj.name, code: pickerObj.code, selectedIndex: currIndex)
            tempVal = true
        }
        //回调是否为空？
        if let returnClosure = self.operationClosure {
            returnClosure(tempVal, valueObj)
        }
    }
    
    private func safeArea() -> CGFloat {
        
        //结果
        var resultVal: CGFloat = 0.0
        //主要是判断是否有“刘海”屏，并且根据做一些相应的适配
        if #available(iOS 11.0, *) {
            let windowwObj = UIApplication.shared.windows
            if windowwObj.count > 0 {
                resultVal = windowwObj.first!.safeAreaInsets.bottom
            }
        }
        //返回
        return resultVal
    }
    
    private func button(with frame: CGRect, title: String, textColor: UIColor, tag: Int) -> UIButton {
        
        //创建
        let tempButton = UIButton(type: .custom)
        tempButton.frame = frame
        tempButton.setTitle(title, for: .normal)
        tempButton.tag = tag
        tempButton.addTarget(self, action: #selector(nextTouched(_:)), for: .touchUpInside)
        tempButton.titleLabel?.font = UIFont.systemFont(ofSize: 16.0)
        tempButton.setTitleColor(textColor, for: .normal)
        //返回
        return tempButton
    }
    
    // MARK: - UIPickerView Delegate, DataSource
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        
        return data.count
    }
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
        
        //当前对象
        let tempObj = data[row]
        //属性
        let tempAttr = [NSAttributedString.Key.foregroundColor: NSKVar.C3_COLOR,
                        NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16.0)]
        //显示值
        let tempVal = NSMutableAttributedString(string: tempObj.name, attributes: tempAttr)
        //返回
        return tempVal
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        
        //保存索引
        currIndex = row
    }
}
